import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { BUSINESS_ERROR_CODES } from '../../utils/errorCodes';
import { Prisma } from '@prisma/client';
import { config } from '../../config';

export class ClientVoteController extends BaseController {
  // 获取当前活动
  async getCurrentActivity(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const now = new Date();
      const userId = req.user?.id;
      
      const currentActivity = await prisma.activity.findFirst({
        where: {
          status: 'ACTIVE',
          startTime: { lte: now },
          endTime: { gt: now }
        },
        include: {
          activityArtists: {
            include: {
              artist: {
                select: {
                  id: true,
                  name: true,
                  avatar: true,
                  description: true
                }
              }
            },
            orderBy: { sortOrder: 'asc' }
          }
        }
      });

      if (!currentActivity) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ACTIVITY_NOT_FOUND, '当前没有进行中的活动');
        return;
      }

      // 获取所有艺人的投票统计
      const voteStats = await prisma.vote.groupBy({
        by: ['artistId'],
        where: { activityId: currentActivity.id },
        _sum: {
          voteCount: true
        },
        _count: {
          userId: true
        }
      });

      // 如果用户已登录，获取用户的投票信息
      let userVotes: any[] = [];
      if (userId) {
        console.log('🔍 调试信息 - 用户ID:', userId);
        console.log('🔍 调试信息 - 活动ID:', currentActivity.id);
        
        // 确保用户ID是数字类型
        const numericUserId = typeof userId === 'string' ? parseInt(userId) : userId;
        
        userVotes = await prisma.vote.findMany({
          where: {
            userId: numericUserId,
            activityId: currentActivity.id
          },
          select: {
            artistId: true,
            voteCount: true,
            activityId: true
          }
        });
        
        console.log('🔍 调试信息 - 查询到的用户投票:', userVotes);
      } else {
        console.log('🔍 调试信息 - 用户未登录，userId:', userId);
      }

      // 为每个艺人添加投票信息
      const activityWithVotes = {
        ...currentActivity,
        activityArtists: currentActivity.activityArtists.map(aa => {
          const voteStat = voteStats.find(vs => vs.artistId === aa.artist.id);
          const totalVotes = voteStat?._sum.voteCount || 0;
          const uniqueVoters = voteStat?._count.userId || 0;
          
          const userVote = userVotes.find(v => v.artistId === aa.artist.id);
          
          console.log(`🔍 调试信息 - 艺人 ${aa.artist.name} (ID: ${aa.artist.id}):`);
          console.log(`   - 用户投票记录:`, userVote);
          console.log(`   - hasVoted:`, !!userVote);
          
          return {
            ...aa,
            artist: {
              ...aa.artist,
              avatar: aa.artist.avatar ? `${config.server.appUrl}${aa.artist.avatar}` : '', // 添加完整URL前缀
              hasVoted: !!userVote,
              userVoteCount: userVote?.voteCount || 0,
              totalVotes: totalVotes,           // 该艺人获得的总票数
              uniqueVoters: uniqueVoters         // 为该艺人投票的独立用户数
            }
          };
        })
      };

      // 按投票数量排序艺人列表（票数高的排在前面）
      activityWithVotes.activityArtists.sort((a, b) => {
        const votesA = a.artist.totalVotes;
        const votesB = b.artist.totalVotes;
        
        // 如果票数相同，按原始排序顺序排列
        if (votesA === votesB) {
          return a.sortOrder - b.sortOrder;
        }
        
        // 按票数降序排列（票数高的在前）
        return votesB - votesA;
      });

      ResponseUtils.success(res, activityWithVotes, '获取当前活动成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取活动艺人投票排行榜
  async getActivityVoteLeaderboard(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { activityId } = req.params;
      const { limit = 10 } = req.query;
      const userId = req.user?.id;

      // 检查活动是否存在且正在进行
      const activity = await prisma.activity.findFirst({
        where: {
          id: parseInt(activityId),
          status: 'ACTIVE',
          startTime: { lte: new Date() },
          endTime: { gt: new Date() }
        }
      });

      if (!activity) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ACTIVITY_NOT_FOUND, '活动不存在或已结束');
        return;
      }

      // 获取活动艺人列表
      const activityArtists = await prisma.activityArtist.findMany({
        where: { activityId: parseInt(activityId) },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          }
        },
        orderBy: { sortOrder: 'asc' }
      });

      // 获取每个艺人的投票统计
      const voteStats = await prisma.vote.groupBy({
        by: ['artistId'],
        where: { activityId: parseInt(activityId) },
        _sum: {
          voteCount: true
        },
        _count: {
          userId: true
        }
      });

      // 合并数据并检查用户是否已投票
      const leaderboard = await Promise.all(
        activityArtists.map(async (aa) => {
          const voteStat = voteStats.find(vs => vs.artistId === aa.artist.id);
          const totalVotes = voteStat?._sum.voteCount || 0;
          const uniqueVoters = voteStat?._count.userId || 0;
          
          let hasVoted = false;
          if (userId) {
            const userVote = await prisma.vote.findUnique({
              where: {
                userId_artistId_activityId: {
                  userId,
                  artistId: aa.artist.id,
                  activityId: parseInt(activityId)
                }
              }
            });
            hasVoted = !!userVote;
          }

          return {
            artistId: aa.artist.id,
            artistName: aa.artist.name,
            artistAvatar: aa.artist.avatar,
            voteCount: totalVotes,
            uniqueVoters,
            hasVoted,
            sortOrder: aa.sortOrder
          };
        })
      );

      // 按投票数排序
      leaderboard.sort((a, b) => b.voteCount - a.voteCount);

      // 添加排名
      const rankedLeaderboard = leaderboard
        .slice(0, Number(limit))
        .map((item, index) => ({
          ...item,
          rank: index + 1
        }));

      ResponseUtils.success(res, {
        activity,
        leaderboard: rankedLeaderboard
      }, '获取投票排行榜成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取投票排行榜（兼容旧版本）
  async getVoteLeaderboard(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { limit = 10 } = req.query;

      // 先获取所有投票数据，然后在应用层进行分组和排序
      const votes = await prisma.vote.findMany({
        select: {
          artistId: true,
          voteCount: true,
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          }
        }
      });

      // 在应用层进行分组和聚合
      const voteMap = new Map<number, { artistId: number; artistName: string; artistAvatar: string; voteCount: number }>();
      
      votes.forEach(vote => {
        const artistId = vote.artistId;
        if (voteMap.has(artistId)) {
          const existing = voteMap.get(artistId)!;
          existing.voteCount += vote.voteCount;
        } else {
          voteMap.set(artistId, {
            artistId: vote.artistId,
            artistName: vote.artist?.name || '未知艺人',
            artistAvatar: vote.artist?.avatar || '',
            voteCount: vote.voteCount
          });
        }
      });

      // 转换为数组并排序
      const leaderboard = Array.from(voteMap.values())
        .sort((a, b) => b.voteCount - a.voteCount)
        .slice(0, Number(limit))
        .map((item, index) => ({
          ...item,
          rank: index + 1
        }));

      ResponseUtils.success(res, leaderboard, '获取投票排行榜成功');
    } catch (error) {
      next(error);
    }
  }

  // 投票
  async vote(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { artistId, activityId } = req.body;
      const userId = req.user?.id;
      
      if (!userId) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.USER_NOT_FOUND, '用户不存在');
        return;
      }

      if (!activityId) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ACTIVITY_NOT_FOUND, '活动ID不能为空');
        return;
      }

      // 检查活动是否存在且正在进行
      const activity = await prisma.activity.findFirst({
        where: {
          id: parseInt(activityId),
          status: 'ACTIVE',
          startTime: { lte: new Date() },
          endTime: { gt: new Date() }
        }
      });

      if (!activity) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ACTIVITY_NOT_FOUND, '活动不存在或已结束');
        return;
      }

      // 检查艺人是否在活动中
      const activityArtist = await prisma.activityArtist.findUnique({
        where: {
          activityId_artistId: {
            activityId: parseInt(activityId),
            artistId: parseInt(artistId)
          }
        }
      });

      if (!activityArtist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_NOT_FOUND, '该艺人未参与此活动');
        return;
      }

      // 检查用户是否已经投过票
      const existingVote = await prisma.vote.findUnique({
        where: {
          userId_artistId_activityId: {
            userId: userId,
            artistId: parseInt(artistId),
            activityId: parseInt(activityId)
          }
        }
      });

      if (existingVote) {
        try {
          // 更新投票数量
          const updatedVote = await prisma.vote.update({
            where: {
              id: existingVote.id
            },
            data: {
              voteCount: existingVote.voteCount + 1
            }
          });

          ResponseUtils.success(res, {
            artistId: updatedVote.artistId,
            activityId: updatedVote.activityId,
            voteCount: updatedVote.voteCount,
            message: '投票成功，已更新您的投票数量'
          }, '投票成功');
        } catch (error) {
          // 处理数据库更新错误
          if (error instanceof Prisma.PrismaClientKnownRequestError) {
            if (error.code === 'P2025') {
              // 记录不存在错误
              ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.VOTE_UPDATE_FAILED, '投票更新失败，记录不存在');
              return;
            }
          }
          // 重新抛出其他错误
          throw error;
        }
      } else {
        try {
          // 创建新投票
          const newVote = await prisma.vote.create({
            data: {
              userId: userId,
              artistId: parseInt(artistId),
              activityId: parseInt(activityId),
              voteCount: 1
            }
          });

          ResponseUtils.success(res, {
            artistId: newVote.artistId,
            activityId: newVote.activityId,
            voteCount: newVote.voteCount,
            message: '投票成功'
          }, '投票成功');
        } catch (error) {
          // 处理数据库创建错误
          if (error instanceof Prisma.PrismaClientKnownRequestError) {
            if (error.code === 'P2002') {
              // 唯一约束违反
              ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.VOTE_ALREADY_EXISTS, '您已经为该艺人投过票了');
              return;
            }
          }
          // 重新抛出其他错误
          throw error;
        }
      }
    } catch (error) {
      next(error);
    }
  }

  // 检查用户投票状态
  async getVoteStatus(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = req.user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.USER_NOT_FOUND, '用户不存在');
        return;
      }

      const { activityId } = req.query;
      if (!activityId) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ACTIVITY_NOT_FOUND, '活动ID不能为空');
        return;
      }

      // 获取用户在该活动中的所有投票
      const userVotes = await prisma.vote.findMany({
        where: {
          userId: userId,
          activityId: parseInt(activityId as string)
        },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          }
        }
      });

      ResponseUtils.success(res, {
        activityId: parseInt(activityId as string),
        votes: userVotes,
        totalVotes: userVotes.reduce((sum, vote) => sum + vote.voteCount, 0)
      }, '获取投票状态成功');
    } catch (error) {
      next(error);
    }
  }
}